package com.example.airole.common.util;

import com.example.airole.common.entity.AudioInfo;
import org.springframework.web.multipart.MultipartFile;

import javax.sound.sampled.AudioFileFormat;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import java.io.File;
import java.io.IOException;

/**
 * 音频工具类
 */
public class AudioUtils {
    
    /**
     * 获取音频文件信息
     */
    public static AudioInfo getAudioInfo(String filePath) throws IOException {
        File audioFile = new File(filePath);
        if (!audioFile.exists()) {
            throw new IOException("音频文件不存在: " + filePath);
        }
        
        try (AudioInputStream audioInputStream = AudioSystem.getAudioInputStream(audioFile)) {
            AudioFileFormat audioFileFormat = AudioSystem.getAudioFileFormat(audioFile);
            
            return AudioInfo.builder()
                    .filePath(filePath)
                    .format(FileUtils.getFileExtension(audioFile.getName()))
                    .sampleRate((int) audioFileFormat.getFormat().getSampleRate())
                    .channels(audioFileFormat.getFormat().getChannels())
                    .duration(calculateDuration(audioFile))
                    .fileSize(audioFile.length())
                    .encoding(audioFileFormat.getFormat().getEncoding().toString())
                    .bitRate(calculateBitRate(audioFileFormat))
                    .build();
        } catch (Exception e) {
            throw new IOException("无法读取音频文件信息: " + e.getMessage(), e);
        }
    }
    
    /**
     * 获取上传音频文件信息
     */
    public static AudioInfo getAudioInfo(MultipartFile file) throws IOException {
        if (file.isEmpty()) {
            throw new IOException("音频文件为空");
        }
        
        String originalFilename = file.getOriginalFilename();
        if (originalFilename == null || !FileUtils.isSupportedAudioFormat(originalFilename)) {
            throw new IOException("不支持的音频格式");
        }
        
        // 创建临时文件
        File tempFile = File.createTempFile("audio_", "." + FileUtils.getFileExtension(originalFilename));
        try {
            file.transferTo(tempFile);
            return getAudioInfo(tempFile.getAbsolutePath());
        } finally {
            // 清理临时文件
            tempFile.delete();
        }
    }
    
    /**
     * 计算音频时长
     */
    private static Double calculateDuration(File audioFile) {
        try (AudioInputStream audioInputStream = AudioSystem.getAudioInputStream(audioFile)) {
            long frames = audioInputStream.getFrameLength();
            double durationInSeconds = (frames + 0.0) / audioInputStream.getFormat().getFrameRate();
            return durationInSeconds;
        } catch (Exception e) {
            return 0.0;
        }
    }
    
    /**
     * 计算比特率
     */
    private static Integer calculateBitRate(AudioFileFormat audioFileFormat) {
        return (int) (audioFileFormat.getFormat().getSampleRate() * 
                     audioFileFormat.getFormat().getSampleSizeInBits() * 
                     audioFileFormat.getFormat().getChannels());
    }
    
    /**
     * 验证音频文件
     */
    public static boolean isValidAudioFile(MultipartFile file) {
        if (file.isEmpty()) {
            return false;
        }
        
        String filename = file.getOriginalFilename();
        if (filename == null) {
            return false;
        }
        
        return FileUtils.isSupportedAudioFormat(filename) && 
               FileUtils.isAudioFileSizeValid(file.getSize());
    }
    
    /**
     * 转换音频格式
     */
    public static String convertAudioFormat(String inputPath, String outputFormat) throws IOException {
        // 这里可以实现音频格式转换逻辑
        // 可以使用FFmpeg或其他音频处理库
        throw new UnsupportedOperationException("音频格式转换功能待实现");
    }
}

